package com.example.psychologicalappointmentsystem.service.impl.user;

import com.example.psychologicalappointmentsystem.Controller.transform.DOToVo;
import com.example.psychologicalappointmentsystem.Entity.ConsultationExtentDO;
import com.example.psychologicalappointmentsystem.Entity.User;
import com.example.psychologicalappointmentsystem.Enum.UploadFileType;
import com.example.psychologicalappointmentsystem.Enum.UserRole;
import com.example.psychologicalappointmentsystem.JpaRepository.ConsultationExtentRepository;
import com.example.psychologicalappointmentsystem.JpaRepository.UserRepository;
import com.example.psychologicalappointmentsystem.Object.UserLoginRequest;
import com.example.psychologicalappointmentsystem.config.auth.PsyThreadLocalUtil;
import com.example.psychologicalappointmentsystem.service.UserService;
import com.example.psychologicalappointmentsystem.tools.FileUploadUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;


@Service
@Slf4j
public class UserServiceImpl implements UserService {

    @Autowired
    private UserRepository userRepository;
    @Autowired
    private ConsultationExtentRepository consultationExtentRepository;

    @Autowired
    private BCryptPasswordEncoder bCryptPasswordEncoder;

    @Autowired
    private DOToVo doToVo;

    @Override
    public ResponseEntity<?> userInfo() {

        try {
            Long userId = PsyThreadLocalUtil.get().getUserId();
            // 根据用户id查询用户
            User foundUser = userRepository.findById(userId).get();
            foundUser.setPassword("");
            UserLoginRequest userVO = new UserLoginRequest();

            BeanUtils.copyProperties(foundUser, userVO);

            //如果是咨询师会有另外的字段
            if (foundUser.getRole() == UserRole.CONSULTANT) {
                ConsultationExtentDO consultationExtentDO = consultationExtentRepository.findByConsultantId(userId);
                // 检查 consultationExtentDO 是否为 null
                if (consultationExtentDO != null) {
                    userVO.setGoodAt(StringUtils.defaultIfEmpty(consultationExtentDO.getGoodAt(),""));
                    userVO.setIndividual(StringUtils.defaultIfEmpty(consultationExtentDO.getIndividual(),""));
                    userVO.setWage(StringUtils.defaultIfEmpty(consultationExtentDO.getWage(),""));
                    userVO.setTencentMeetingCode(StringUtils.defaultIfEmpty(consultationExtentDO.getTencentmeetingcode(),""));
                    userVO.setAliPayCode(StringUtils.defaultIfEmpty(consultationExtentDO.getAlipaycode(),""));
                } else {
                    userVO.setIndividual("");
                    userVO.setGoodAt("");
                    userVO.setWage("");
                    userVO.setTencentMeetingCode("");
                    userVO.setAliPayCode("");
                }
            }


            return ResponseEntity.ok(userVO);
        } catch (Exception e) {
            log.error("获取用户信息异常！" + e.getMessage(), e);
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("获取用户信息异常！");
        }
    }

    @Override
    public ResponseEntity<?> userInfoUpdate(UserLoginRequest loginRequest) {
        try {
            Long userId = PsyThreadLocalUtil.get().getUserId();
            // 根据用户id查询用户
            User foundUser = userRepository.findById(userId).get();
            foundUser.setEmail(loginRequest.getEmail());
            foundUser.setRegion(loginRequest.getRegion());
            foundUser.setQualificationImage(loginRequest.getQualificationImage());
            foundUser.setNickname(loginRequest.getNickname());

            //如果有给密码，就校验下
            String newPasswd = loginRequest.getPassword();
            if (StringUtils.isNotEmpty(newPasswd)) {
                //修改密码，先校验下密码是否被修改过，如过没改就还用原来的。
                String oldPasswd = foundUser.getPassword();
                // 加密密码
                String encodedPassword = bCryptPasswordEncoder.encode(newPasswd);
                if (!oldPasswd.equals(encodedPassword)) {
                    foundUser.setPassword(loginRequest.getPassword());
                }else {
                    foundUser.setPassword(oldPasswd);
                }
            }
            userRepository.save(foundUser);
            //如果是咨询师会有另外的字段
            if (foundUser.getRole() == UserRole.CONSULTANT) {
                //如果修改的是咨询师，还有另外的扩展字段
                ConsultationExtentDO consultationExtentDO = consultationExtentRepository.findByConsultantId(userId);
                if (Objects.nonNull(consultationExtentDO)){
                    consultationExtentDO.setIndividual(loginRequest.getIndividual());
                    consultationExtentDO.setGoodAt(loginRequest.getGoodAt());
                    consultationExtentDO.setWage(loginRequest.getWage());
                    consultationExtentDO.setTencentmeetingcode(loginRequest.getTencentMeetingCode());
                    consultationExtentDO.setAlipaycode(loginRequest.getAliPayCode());
                }else {
                    consultationExtentDO = new ConsultationExtentDO();
                    consultationExtentDO.setConsultantId(userId);
                    consultationExtentDO.setIndividual(loginRequest.getIndividual());
                    consultationExtentDO.setGoodAt(loginRequest.getGoodAt());
                    consultationExtentDO.setWage(loginRequest.getWage());
                    consultationExtentDO.setTencentmeetingcode(loginRequest.getTencentMeetingCode());
                    consultationExtentDO.setAlipaycode(loginRequest.getAliPayCode());
                }

                //保存
                consultationExtentRepository.save(consultationExtentDO);
            }

            return ResponseEntity.ok("保存用户信息成功");
        } catch (Exception e) {
            log.error("保存用户信息失败！" + e.getMessage(), e);
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("保存用户信息失败！");
        }

    }

    @Override
    public ResponseEntity<?> userListPage(UserLoginRequest loginRequest) {
        try {
            loginRequest.initDefaultPageSize();
            Pageable pageable = PageRequest.of(loginRequest.getCurrent(), loginRequest.getPageSize());

            //去数据库分页查询数据
            Page<User> consultationUserListPage = userRepository.findByRole(UserRole.CONSULTANT, pageable);

            // page转换成vo返回
            List<UserLoginRequest> userVos = consultationUserListPage.stream()
                    .map(user -> doToVo.userDo_to_userVo(user))
                    .collect(Collectors.toList());

            // 创建一个新的 Page 对象，使用修改后的 content 和原始 page 的其他信息
            Page<UserLoginRequest> userVOS1 = DOToVo.updatePageContent(consultationUserListPage,userVos);


            return ResponseEntity.ok(userVOS1);
        } catch (Exception e) {
            log.error("获取咨询师列表异常！" + e.getMessage(), e);
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("获取咨询师列表异常！");
        }
    }

    @Override
    public ResponseEntity<?> userHeadImageUpload(MultipartFile file) {
        try {
            // 保存文件并获取路径
            String avatarPath = FileUploadUtil.saveFile(file, UploadFileType.HEADIMAGE);

            Long userId = PsyThreadLocalUtil.get().getUserId();
            User userDO = userRepository.findById(userId).get();

            userDO.setImgPath(avatarPath);

            userRepository.save(userDO);

            return ResponseEntity.ok("用户头像保存成功");
        } catch (Exception e) {
            log.error("上传文件操作异常" + e.getMessage(), e);
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("上传文件操作异常！");
        }
    }
}
